import CloudManager from '../network/cloudManager'

export default class RoomJoinTest {
  constructor() {
    this.cloudManager = new CloudManager()
    this.testResults = []
  }

  async runAllTests() {
    console.log('开始运行房间加入功能测试...')
    
    await this.testRoomCreation()
    await this.testRoomValidation()
    await this.testRoomJoinProcess()
    await this.testDatabaseSync()
    await this.testGameStartDetection()
    
    this.printResults()
  }

  async testRoomCreation() {
    console.log('测试：房间创建功能')
    
    try {
      // 模拟房间创建
      const roomId = await this.cloudManager.createRoom()
      
      const result = roomId && roomId.length > 0
      this.testResults.push({
        name: '房间创建功能',
        passed: result,
        message: result ? '测试通过' : '测试失败：房间创建失败'
      })
      
      // 清理测试房间
      await this.cleanupTestRoom(roomId)
      
    } catch (error) {
      this.testResults.push({
        name: '房间创建功能',
        passed: false,
        message: `测试失败：${error.message}`
      })
    }
  }

  async testRoomValidation() {
    console.log('测试：房间验证功能')
    
    try {
      // 创建测试房间
      const roomId = await this.cloudManager.createRoom()
      
      // 验证房间存在
      const validation = await this.cloudManager.validateRoom(roomId)
      
      const result = validation.exists && validation.room
      this.testResults.push({
        name: '房间验证功能',
        passed: result,
        message: result ? '测试通过' : '测试失败：房间验证失败'
      })
      
      // 清理测试房间
      await this.cleanupTestRoom(roomId)
      
    } catch (error) {
      this.testResults.push({
        name: '房间验证功能',
        passed: false,
        message: `测试失败：${error.message}`
      })
    }
  }

  async testRoomJoinProcess() {
    console.log('测试：房间加入流程')
    
    try {
      // 创建测试房间
      const roomId = await this.cloudManager.createRoom()
      
      // 模拟加入房间
      const joinResult = await this.cloudManager.joinRoom(roomId)
      
      const result = joinResult === roomId
      this.testResults.push({
        name: '房间加入流程',
        passed: result,
        message: result ? '测试通过' : '测试失败：房间加入失败'
      })
      
      // 清理测试房间
      await this.cleanupTestRoom(roomId)
      
    } catch (error) {
      this.testResults.push({
        name: '房间加入流程',
        passed: false,
        message: `测试失败：${error.message}`
      })
    }
  }

  async testDatabaseSync() {
    console.log('测试：数据库同步功能')
    
    try {
      // 创建测试房间
      const roomId = await this.cloudManager.createRoom()
      
      // 获取房间初始状态
      const initialRoom = await this.getRoomData(roomId)
      
      // 模拟加入房间
      await this.cloudManager.joinRoom(roomId)
      
      // 等待数据库同步
      await new Promise(resolve => setTimeout(resolve, 2000))
      
      // 获取更新后的房间状态
      const updatedRoom = await this.getRoomData(roomId)
      
      const result = updatedRoom && 
                    updatedRoom.status === 'playing' && 
                    updatedRoom.player2 && 
                    updatedRoom.currentPlayer
      
      this.testResults.push({
        name: '数据库同步功能',
        passed: result,
        message: result ? '测试通过' : '测试失败：数据库同步失败'
      })
      
      // 清理测试房间
      await this.cleanupTestRoom(roomId)
      
    } catch (error) {
      this.testResults.push({
        name: '数据库同步功能',
        passed: false,
        message: `测试失败：${error.message}`
      })
    }
  }

  async testGameStartDetection() {
    console.log('测试：游戏开始检测功能')
    
    try {
      // 创建测试房间
      const roomId = await this.cloudManager.createRoom()
      
      // 设置游戏开始回调
      let gameStarted = false
      this.cloudManager.onGameStart = () => {
        gameStarted = true
        console.log('游戏开始回调触发')
      }
      
      // 模拟加入房间
      await this.cloudManager.joinRoom(roomId)
      
      // 等待游戏开始检测
      await new Promise(resolve => setTimeout(resolve, 3000))
      
      const result = gameStarted
      this.testResults.push({
        name: '游戏开始检测功能',
        passed: result,
        message: result ? '测试通过' : '测试失败：游戏开始检测失败'
      })
      
      // 清理测试房间
      await this.cleanupTestRoom(roomId)
      
    } catch (error) {
      this.testResults.push({
        name: '游戏开始检测功能',
        passed: false,
        message: `测试失败：${error.message}`
      })
    }
  }

  async getRoomData(roomId) {
    try {
      const roomResult = await this.cloudManager.db.collection('rooms')
        .where({
          roomId: roomId
        })
        .get()
      
      return roomResult.data.length > 0 ? roomResult.data[0] : null
    } catch (error) {
      console.error('获取房间数据失败:', error)
      return null
    }
  }

  async cleanupTestRoom(roomId) {
    try {
      if (roomId) {
        const roomResult = await this.cloudManager.db.collection('rooms')
          .where({
            roomId: roomId
          })
          .get()
        
        if (roomResult.data.length > 0) {
          await this.cloudManager.db.collection('rooms')
            .doc(roomResult.data[0]._id)
            .remove()
          console.log('清理测试房间:', roomId)
        }
      }
    } catch (error) {
      console.error('清理测试房间失败:', error)
    }
  }

  printResults() {
    console.log('\n=== 房间加入功能测试结果 ===')
    let passedCount = 0
    let totalCount = this.testResults.length
    
    this.testResults.forEach((test, index) => {
      const status = test.passed ? '✅ 通过' : '❌ 失败'
      console.log(`${index + 1}. ${test.name}: ${status}`)
      if (!test.passed) {
        console.log(`   原因: ${test.message}`)
      } else {
        passedCount++
      }
    })
    
    console.log(`\n总计: ${passedCount}/${totalCount} 测试通过`)
    
    if (passedCount === totalCount) {
      console.log('🎉 所有测试通过！房间加入功能正常。')
    } else {
      console.log('⚠️  部分测试失败，需要检查代码。')
    }
  }
} 